import { useState, useEffect } from 'react'
import { useAuth } from '../contexts/AuthProvider'

export interface Notification {
  id: string
  title: string
  message: string
  type: 'info' | 'success' | 'warning' | 'error' | 'paper_alert'
  read: boolean
  created_at: string
  action_url?: string
  metadata?: {
    paper_id?: string
    paper_title?: string
    arxiv_id?: string
  }
}

interface UseNotificationsReturn {
  notifications: Notification[]
  unreadCount: number
  loading: boolean
  markAsRead: (id: string) => Promise<void>
  markAllAsRead: () => Promise<void>
  deleteNotification: (id: string) => Promise<void>
  fetchNotifications: () => Promise<void>
}

export function useNotifications(): UseNotificationsReturn {
  const [notifications, setNotifications] = useState<Notification[]>([])
  const [loading, setLoading] = useState(false)
  const { user } = useAuth()

  // Mock notifications data
  const mockNotifications: Notification[] = [
    {
      id: '1',
      title: 'New Paper Alert',
      message: 'Found 3 new papers matching "transformer attention"',
      type: 'paper_alert',
      read: false,
      created_at: '2024-01-20T10:00:00Z',
      action_url: '/app/browse?alert=1'
    },
    {
      id: '2',
      title: 'Weekly Digest Ready',
      message: 'Your personalized research digest for this week is available',
      type: 'info',
      read: false,
      created_at: '2024-01-19T09:00:00Z',
      action_url: '/app/notifications/digest'
    },
    {
      id: '3',
      title: 'Paper Recommendation',
      message: 'New paper in your field: "Attention Is All You Need"',
      type: 'paper_alert',
      read: true,
      created_at: '2024-01-18T14:30:00Z',
      metadata: {
        paper_id: '1',
        paper_title: 'Attention Is All You Need',
        arxiv_id: '2301.00001'
      }
    },
    {
      id: '4',
      title: 'Reading Goal Achievement',
      message: 'Congratulations! You\'ve reached your weekly reading goal of 5 papers',
      type: 'success',
      read: true,
      created_at: '2024-01-17T16:45:00Z'
    }
  ]

  const unreadCount = notifications.filter(n => !n.read).length

  const fetchNotifications = async () => {
    if (!user) return
    
    setLoading(true)
    try {
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 500))
      setNotifications(mockNotifications)
    } catch (error) {
      console.error('Error fetching notifications:', error)
    } finally {
      setLoading(false)
    }
  }

  const markAsRead = async (id: string) => {
    try {
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 200))
      setNotifications(prev => 
        prev.map(n => n.id === id ? { ...n, read: true } : n)
      )
    } catch (error) {
      console.error('Error marking notification as read:', error)
    }
  }

  const markAllAsRead = async () => {
    try {
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 300))
      setNotifications(prev => prev.map(n => ({ ...n, read: true })))
    } catch (error) {
      console.error('Error marking all notifications as read:', error)
    }
  }

  const deleteNotification = async (id: string) => {
    try {
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 200))
      setNotifications(prev => prev.filter(n => n.id !== id))
    } catch (error) {
      console.error('Error deleting notification:', error)
    }
  }

  // Load notifications when user is available
  useEffect(() => {
    if (user) {
      fetchNotifications()
    }
  }, [user])

  return {
    notifications,
    unreadCount,
    loading,
    markAsRead,
    markAllAsRead,
    deleteNotification,
    fetchNotifications
  }
}